package SellTicket;

public class SellTicket_improve {
    public static void main(String[] args) {
        sell03 sell03 = new sell03();
        new Thread(sell03).start();
        new Thread(sell03).start();
        new Thread(sell03).start();

    }
}
class sell03 implements Runnable {
    private int ticketNum = 100;//让多个线程共享ticketNum
    private boolean loop = true;
    @Override
    public void run() {//这就是一个同步方法，锁的是this，也可以在代码块上写synchronize同步代码块
        while (loop) {
            synchronized (this) {
                if (ticketNum <= 0) {
                    System.out.println("售票结束...");
                    loop = false;
                    return;
                }
//休眠 50 毫秒, 模拟
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("窗口 " + Thread.currentThread().getName() + " 售出一张票" + " 剩余票数=" + (--ticketNum));
            }
        }
    }
}


